package com.ruoyi.common.utils.photo;

import com.drew.imaging.ImageMetadataReader;
import com.drew.metadata.Metadata;
import com.drew.metadata.exif.ExifSubIFDDirectory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;

public class PhotoMetadataExtractor {

    private static final Set<String> IMAGE_EXTENSIONS = new HashSet<>(Arrays.asList(
            ".jpg", ".jpeg", ".png", ".tiff", ".bmp", ".gif", ".cr2", ".nef", ".arw"
    ));

    public static void main(String[] args) {
        // 设置图片根目录 - 请修改为您的实际路径
        String rootPath = "C:\\Users\\xinhuiRong\\Desktop\\宠物\\宠物";
        System.out.println("开始处理图片元数据，根目录: " + rootPath);
        processAllImages(rootPath);
        System.out.println("元数据处理完成！");
    }

    public static void processAllImages(String rootPath) {
        try {
            long startTime = System.currentTimeMillis();
            int processedCount = 0;
            int errorCount = 0;

            System.out.println("开始扫描目录: " + rootPath);
            for (Path path : (Iterable<Path>) Files.walk(Paths.get(rootPath))::iterator) {
                if (Files.isRegularFile(path)) {
                    String fileName = path.toString().toLowerCase();
                    boolean isImage = IMAGE_EXTENSIONS.stream().anyMatch(fileName::endsWith);

                    if (isImage) {
                        System.out.println("发现图片文件: " + path);
                        try {
                            processSingleImage(path);
                            processedCount++;
                        } catch (Exception e) {
                            System.err.println("处理失败: " + path + " - " + e.getMessage());
                            errorCount++;
                        }
                    }
                }
            }

            long duration = System.currentTimeMillis() - startTime;
            System.out.println("\n处理摘要:");
            System.out.println("  扫描目录: " + rootPath);
            System.out.println("  处理图片: " + processedCount + " 张");
            System.out.println("  失败数量: " + errorCount + " 张");
            System.out.println("  耗时: " + duration + " 毫秒");
        } catch (IOException e) {
            System.err.println("遍历文件夹失败: " + e.getMessage());
        }
    }

    private static void processSingleImage(Path imagePath) throws Exception {
        System.out.println("处理中: " + imagePath.getFileName());

        // 提取元数据
        Map<String, String> params = extractShootingParams(imagePath.toFile());

        // 创建JSON文件路径
        String imageName = imagePath.getFileName().toString();
        int dotIndex = imageName.lastIndexOf('.');
        if (dotIndex == -1) {
            throw new IllegalArgumentException("文件名缺少扩展名: " + imageName);
        }

        String baseName = imageName.substring(0, dotIndex);
        Path jsonPath = imagePath.resolveSibling(baseName + ".json");

        // 写入JSON文件
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.writeValue(jsonPath.toFile(), params);

        System.out.println("  生成元数据: " + jsonPath.getFileName());
    }

    public static Map<String, String> extractShootingParams(File imageFile) {
        Map<String, String> params = new LinkedHashMap<>();

        // 初始化默认值
        params.put("焦段", "N/A");
        params.put("光圈值", "N/A");
        params.put("感光度", "N/A");
        params.put("快门速度", "N/A");
        params.put("曝光补偿", "N/A");
//        params.put("自动白平衡值", "N/A");
//        params.put("拍摄方向", "N/A");
//        params.put("摄影师位置", "N/A");

        try {
            Metadata metadata = ImageMetadataReader.readMetadata(imageFile);
            ExifSubIFDDirectory exifDir = metadata.getFirstDirectoryOfType(ExifSubIFDDirectory.class);

            if (exifDir != null) {
                // 焦段
                if (exifDir.containsTag(ExifSubIFDDirectory.TAG_FOCAL_LENGTH)) {
                    double focalLength = exifDir.getDouble(ExifSubIFDDirectory.TAG_FOCAL_LENGTH);
                    params.put("焦段", String.format("%.1f mm", focalLength));
                }

                // 光圈值
                if (exifDir.containsTag(ExifSubIFDDirectory.TAG_FNUMBER)) {
                    double fnumber = exifDir.getDouble(ExifSubIFDDirectory.TAG_FNUMBER);
                    params.put("光圈值", String.format("f/%.1f", fnumber));
                }

                // 感光度
                if (exifDir.containsTag(ExifSubIFDDirectory.TAG_ISO_EQUIVALENT)) {
                    int iso = exifDir.getInt(ExifSubIFDDirectory.TAG_ISO_EQUIVALENT);
                    params.put("感光度", "ISO " + iso);
                }

                // 快门速度
                if (exifDir.containsTag(ExifSubIFDDirectory.TAG_EXPOSURE_TIME)) {
                    double exposure = exifDir.getDouble(ExifSubIFDDirectory.TAG_EXPOSURE_TIME);
                    if (exposure < 1.0) {
                        params.put("快门速度", "1/" + (int) Math.round(1/exposure));
                    } else {
                        params.put("快门速度", String.format("%.1f 秒", exposure));
                    }
                }

                // 曝光补偿
                if (exifDir.containsTag(ExifSubIFDDirectory.TAG_EXPOSURE_BIAS)) {
                    double bias = exifDir.getDouble(ExifSubIFDDirectory.TAG_EXPOSURE_BIAS);
                    params.put("曝光补偿", String.format("%.1f EV", bias));
                }

                // 自动白平衡值
                if (exifDir.containsTag(ExifSubIFDDirectory.TAG_WHITE_BALANCE)) {
                    try {
                        String wbDesc = exifDir.getDescription(ExifSubIFDDirectory.TAG_WHITE_BALANCE);
                        if (wbDesc != null) {
                            params.put("自动白平衡值", wbDesc.contains("Auto") ? "自动" : "手动");
                        }
                    } catch (Exception e) {
                        // 忽略白平衡解析错误
                    }
                }

                // 拍摄方向 (从ExifSubIFDDirectory移动到ExifIFD0Directory)
                try {
                    if (exifDir.containsTag(ExifSubIFDDirectory.TAG_ORIENTATION)) {
                        int orientation = exifDir.getInt(ExifSubIFDDirectory.TAG_ORIENTATION);
                        params.put("拍摄方向", (orientation == 1 || orientation == 3) ? "水平" : "垂直");
                    }
                } catch (Exception e) {
                    // 忽略方向解析错误
                }
            } else {
                System.out.println("  警告: 图片缺少EXIF数据 - " + imageFile.getName());
            }
        } catch (Exception e) {
            System.err.println("  读取元数据失败: " + imageFile.getName() + " - " + e.getMessage());
        }

        return params;
    }
}